package net.zxjava.gateway.filters;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import net.zxjava.gateway.route.ZxjavaRouteLocator;

/**
 * 动态路由拦截器
 */
public class PreRouteFilter extends ZuulFilter {
	private Logger logger = LoggerFactory.getLogger(PreRouteFilter.class);

	private static final String SERVER_NAME = "serverName";
	private static final String SET_LOGIC_SERVER = "/setServer";
	private static String currentServerName = "";

	@Resource
	private ZxjavaRouteLocator zxjavaRouteLocator;

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		String requestUrl = request.getServletPath();
		String serverName = "";

		switch (requestUrl) {
		case SET_LOGIC_SERVER: // 设置路由规则请求
			serverName = request.getParameter(SERVER_NAME);
			Cookie serverNameCookie = new Cookie(SERVER_NAME, serverName);
			serverNameCookie.setDomain("zxjava.net");
			serverNameCookie.setPath("/");
			ctx.getResponse().addCookie(serverNameCookie);
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(200);
			ctx.setResponseBody(JSONObject.toJSONString("the current server is " + serverName));
			break;
		default: // 正常请求
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					if (StringUtils.equals(cookie.getName(), SERVER_NAME)) { // cookie中已经存在serverName
						serverName = cookie.getValue();
						break;
					}
				}
			}
			break;
		}

		refreshRouteRulesIfNecessary(serverName);

		return null;
	}

	private synchronized void refreshRouteRulesIfNecessary(String serverName) {
		if (StringUtils.equals(serverName, currentServerName)) {
			return;
		}
		logger.info("当前serverName: {}和请求携带的serverName: {}不一致, 执行一次路由规则刷新", currentServerName, serverName);
		zxjavaRouteLocator.doRefresh(serverName);
		currentServerName = serverName;
	}
}
